import { think } from "thinkjs";
import Base, { ServiceOption } from "../../../../../service/base";
import { autoFormatData, RestModelClass, RestOption } from '../../../../../types/utils/rest';

import { ISnsProfile } from '../../types';
import { IServiceSnsThreadGetParams } from "../../types/service/thread";
import SnsProfileModelClass from "../model/profile";

export class ProfileServiceClass extends Base {

  /**
   * 新增或更新
   */
  async put(data: ISnsProfile) {
    const auth = await this.checkAuth(null);
    const user_id = auth.user.id;
    const profileModel = this.model('sns_profile') as SnsProfileModelClass;
    const existProfile = await profileModel.where({
      user_id,
    }).field(`user_id`).find();
    let form = autoFormatData({
      photos: 'jsonStringify'
    }, data);
    if (think.isEmpty(existProfile)) {
      const profileId = await profileModel.add({
        ...form,
        user_id
      });
      if (!profileId && profileId !== 0) throw new Err('更新失败 #1');
    } else {
      const updateProfileRes = await profileModel.where({ user_id }).update(form);
      if (updateProfileRes !== 1) throw new Err('更新失败 #2');
    }
    return 'ok';
  }

  async getMyProfile() {
    let auth = await this.checkAuth();
    let option: RestOption<ISnsProfile> = {
      tableName: 'sns_profile',
      privateKey: 'user_id',
      where: {
        user_id: auth.user.id
      },
      queryFormat: {
        photos: 'jsonParse',
        birth: 'dateFormat'
      },
    };
    const restModel = new RestModelClass(option);
    let res = await restModel.get({
      user_id: auth.user.id
    });
    return res;
  }

  async get(params: IServiceSnsThreadGetParams) {
    let auth = await this.checkAuth();
    let option: RestOption<ISnsProfile> = {
      tableName: 'sns_thread',
      privateKey: 'user_id',
      alias: 'gb',
      where: {
        'gb.shop_id': auth.role.shop_id
      },
      queryFormat: {
        create_time: {
          type: 'dateFormatDateTime',
          as: 'start_time_str',
        },
        update_time: {
          type: 'dateFormatDateTime',
          as: 'end_time_str',
        }
      },
    };
    const restModel = new RestModelClass(option);
    let res = await restModel.get(params);
    return res;
  }

  async delete({
    tableName,
    privateKey,
    ...params
  }: any) {
    const auth = await this.checkAuth();
    if (!tableName || !privateKey) throw new Err('缺少参数 tableName | privateKey');
    let option: RestOption<ISnsProfile> = {
      tableName,
      privateKey
    };
    const restModel = new RestModelClass(option);
    return restModel.delete(params);
  }

}

export default ProfileServiceClass;
